package pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:模拟实现线程池
 * User: bjc
 * Date: 2025-09-18
 * Time: 15:11
 */
class MyThreadPoolExecutor {
    //存放工作线程
    private List<Thread> threads = new ArrayList<>();
    //存放任务，使用阻塞队列完成
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);

    //构造方法
    public MyThreadPoolExecutor(int corePoolSize) {
        for (int i = 0; i < corePoolSize; i++) {
            //线程的任务就是把任务队列中的任务取出来，然后进行执行
            Thread t = new Thread(()->{
                while (true){
                    Runnable task = null;
                    try {
                        //此处的take()方法会阻塞，直到有任务加入队列，也就是说如果队列为空，则take()方法会阻塞，直到有任务加入队列
                        task = queue.take();
                        //执行任务
                        task.run();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            //启动线程
            t.start();
            //添加线程
            threads.add(t);
        }
    }
    public void submit(Runnable task) throws InterruptedException {
        //把任务加入队列
        queue.put(task);
    }
}

public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPoolExecutor executor = new MyThreadPoolExecutor(4);
        for (int i = 0; i < 1000; i++) {
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                }
            });
        }
    }
}
